import { customComponent } from "@utils/customComponent.js";
import { properties } from "./props";

const option = customComponent({
    data: {},
    relations: {
        "../checkbox/checkbox": {
            type: "descendant",
            linked: function (target) {
                const { value } = this.data;
                target.setData({
                    checked: value.includes(target.data.value)
                });
            }
        }
    },
    observers: {
        value(val) {
            this.$children.forEach((item) => {
                item.setData({
                    checked: val.includes(item.data.value)
                });
            });
        }
    },
    properties: properties,
    methods: {
        updateValue({ checked, value }) {
            const { value: oldValue } = this.data;
            if (checked) {
                oldValue.push(value);
            } else {
                oldValue.splice(oldValue.indexOf(value), 1);
            }
            this.triggerEvent("change", { value: oldValue });
        }
    }
});
Component(option);
